<template>
  <a-form
    :model="model"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    label-align="left"
    layout="inline"
    class="query-filter flex flex-nowrap"
  >
    <div class="query-layout flex-1" :class="{ 'query-layout--collapse': showExpand }">
      <slot></slot>
    </div>
    <div class="query-filter__operate flex-shrink-0">
      <slot name="operate">
        <a-button type="primary" class="mr-2" @click="emit('submit')">查询</a-button>
        <a-button type="default" @click="emit('reset')">重置</a-button>
        <a-button type="link" class="ml-2 expand" v-if="slotsLen > 3" @click="handleExpand">
          <span v-if="expand">收起<up-outlined class="expand-icon" /></span>
          <span v-else>展开<down-outlined class="expand-icon" /></span>
        </a-button>
      </slot>
    </div>
  </a-form>
</template>

<script lang="ts" setup>
import { computed, ref, useSlots } from 'vue'
import type { FormInstance } from 'ant-design-vue'
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue'

interface Props {
  model?: FormInstance['model']
  rules?: FormInstance['rules']
  labelCol?: FormInstance['labelCol']
  labelWrap?: FormInstance['labelWrap']
  wrapperCol?: FormInstance['wrapperCol']
  showOperate?: boolean
  spans?: number[]
}

interface Emits {
  (e: 'submit'): void
  (e: 'reset'): void
}

const emit = defineEmits<Emits>()

const slots = useSlots()

const slotsLen = computed(() => {
  return (slots?.default?.() ?? []).length
})

const expand = ref(false)

const showExpand = computed(() => {
  return slotsLen.value > 3 && !expand.value
})

withDefaults(defineProps<Props>(), {
  model: undefined,
  rules: undefined,
  labelCol: undefined,
  labelWrap: undefined,
  wrapperCol: undefined,
  showOperate: true
})

function handleExpand() {
  expand.value = !expand.value
}
</script>

<script lang="ts">
export default {
  name: 'QueryFilter'
}
</script>

<style lang="scss" scoped>
.operate {
  width: 102px;

  &__divider {
    margin: 0 14px 0 0;
    height: 100%;
    background: #f1f0f6;
  }

  &__wrapper {
    width: 86px;
  }

  button {
    width: 86px;
  }
}

.query-layout {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  grid-gap: 16px 0;
  overflow: hidden;

  &--collapse {
    height: 32px;
  }
}

.expand {
  padding: 0;
}

.expand-icon {
  margin-left: 2px !important;
}
</style>

<style lang="scss">
.query-filter {
  .ant-col.ant-form-item-control {
    flex-grow: 1;
    overflow: hidden;
  }
}
</style>
